package chagine.core.util;

import chagine.core.restful.util.TResponseObject;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.serializer.SerializerFeature;
import org.apache.commons.lang3.StringUtils;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;

import java.util.Collection;
import java.util.Iterator;
import java.util.Map;

public class ResponseUtil {

    public static ResponseEntity<String> getJsonResponse(HttpStatus httpStatus, TResponseObject responseObject) {
        String responseJson = JSON.toJSONString(responseObject, SerializerFeature.DisableCircularReferenceDetect);
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON_UTF8);
        return ResponseEntity.status(httpStatus).headers(headers).body(responseJson);
    }

    /**
     * 解析下载的文件名
     * form-data; name="attachment"; filename="CT831960_0005_00007_CT_256696041.3.12.2.1107.5.1.4.92348.30000021111500121453700042970.dcm"
     */
    public static String getHeaderFileName(feign.Response response) {
        Map<String, Collection<String>> headers = response.headers();
        Collection<String> stringList = headers.get("Content-Disposition");
        Iterator<String> iterator = stringList.iterator();
        String dispositionHeader = null;
        while (iterator.hasNext()) {
            dispositionHeader = iterator.next();
        }
        if (dispositionHeader == null) {
            return "";
        }
        return getFormDataFileName(dispositionHeader);
    }

    public static String getFormDataFileName(String dispositionHeader) {
        if (!StringUtils.isEmpty(dispositionHeader)) {
            dispositionHeader = dispositionHeader.replace("form-data; ", "");
            String[] strings = dispositionHeader.split("; ");
            if (strings.length > 1) {
                dispositionHeader = strings[1].replace("filename=", "");
                dispositionHeader = dispositionHeader.replace("\"", "");
                return dispositionHeader;
            }
            return "";
        }
        return "";
    }


}
